package xyz.jcat.webflux.sucurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import reactor.core.publisher.Mono;
import xyz.jcat.common.util.CollectionUtils;
import xyz.jcat.security.UserRoleAuthenticationToken;

import java.util.List;

@Slf4j
public abstract class AbstractReactiveAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        log.info("come in ReactiveAuthorizationManager");
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();
        String path = request.getURI().getPath();

        List<Long> needRoleIds = getAuthority(path);
        //不需要认证
        if(CollectionUtils.isEmpty(needRoleIds)) {
            return Mono.just(new AuthorizationDecision(true));
        }

        return mono.map(auth -> {
            UserRoleAuthenticationToken token = (UserRoleAuthenticationToken) auth;
            List<Long> userRoleIds = token.getRoleIds();
            if(CollectionUtils.isEmpty(userRoleIds)) {
                return new AuthorizationDecision(false);
            }
            for (Long userRoleId : userRoleIds) {
                if(needRoleIds.contains(userRoleId)) {
                    return new AuthorizationDecision(true);
                }
            }
            return new AuthorizationDecision(false);
        }).defaultIfEmpty(new AuthorizationDecision(false));
    }

    public abstract List<Long> getAuthority(String path);

}
